// packageA/member/new_userinfo/new_userinfo.js
let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      name: '',
      sex: 0,
      birthday: "",
      detailedAddress: '',
      dataTime: '请选择',
      text: '', //文本
      address: '',
      field: '', //自定义固定字段
      nickname: '', //昵称
    },
    districtName: '', //地址
    district: '',
    sexShow: false, //性别选择弹窗
    birthdayShow: false, //生日选择弹窗
    showAdd: false, //地区选择弹窗
    fixedDiyField: '', //自定义字段(固定)
    diyform: '', //自定义表单
    registerBasicInfo: {},
    nameOfTheMall: '', //商城名称
    userProtocol: '', //用户协议
    diyField: '', //自定义字段
    diyStatus: 0, //是否存在自定义表单
    changeNickname: false, //是否可以更改昵称
    changePicture: false, //是否可以更改头像
    isShowAddress: '',
    selectAddressData: [],
    provinceData: [],
    pickerValue: [0, 0, 0],
    districtData: [],
    minDate: new Date(1900,0,1).getTime(),
    maxDate: new Date(2025,0, 1).getTime(),
    currentDate: new Date().getTime(),
    addressObject: {
      province: '',
      province_name: '',
      city: '',
      city_name: '',
      area: '',
      area_name: '',
    }, //地址对象
    member_id: '',
    info: {},
    form_id: "",
    fileList: [{
      url: "",
      isImage: true
    }], //头像图片
    orderLocationObj: {
      positioning_success: 0,
      register_province: "",
      register_city: ""
    },
    sexLIst: [{ //性别选择列表
      value: "男",
      url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/debt/manNo.png",
      checkedUrl: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/debt/manYes.png",
      checked: false
    }, {
      value: "女",
      url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/debt/womenNo.png",
      checkedUrl: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/debt/womenYes.png",
      checked: false
    }],
    customFormID: '', //自定义表单id
    subject: '', //主题色
    child:'',//自定义表单实例
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.essentialInformation()
    let basic_info = wx.getStorageSync("yz_basic_info").theme_color;
    this.setData({
      subject: basic_info
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //加载地址数据初始化
    this._initAddressInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  sexSwitch(e) { //性别切换
    this.data.sexLIst.forEach((item, index) => {
      let sexListIndex = `sexLIst[${index}].checked`
      if (e.currentTarget.dataset.index == index) {
        this.setData({
          [sexListIndex]: true
        })
        if (e.currentTarget.dataset.index == 1) {
          this.setData({
            'form.sex': 2
          })
        } else {
          this.setData({
            'form.sex': 1
          })
        }
      } else {
        this.setData({
          [sexListIndex]: false
        })
      }
    })
  },

  sexPopup() { //性别弹窗
    this.setData({
      sexShow: !this.data.sexShow
    })
  },

  birthdayPopup() { //生日弹窗
    this.setData({
      birthdayShow: !this.data.birthdayShow
    })
  },

  //时间选择组件方法
  formatDate(date) {
    date = new Date(date);
    return `${date.getYear() + 1900}-${date.getMonth() + 1}-${date.getDate()}`;
  },

  //头像上传
  afterRead(event) {
    console.log('图片', event)
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: event.detail.avatarUrl,
      name: 'file',
      formData: null,
      success: (res) => {
        let _res = JSON.parse(res.data);
        this.setData({
          'fileList[0]': {
            ...event.detail.avatarUrl,
            url: _res.data.img_url
          },
          "form.avatar": _res.data.img
        })
        console.log(this.data.form.avatar, this.data.fileList[0].url)
      },
    });
  },

  onConfirm(event) { //生日时间选择
    this.onClose()
    this.setData({
      'form.birthday': this.formatDate(event.detail)
    })
  },
  onClose() { //关闭生日时间选择弹窗
    this.setData({
      birthdayShow: false
    });
  },

  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log('地址信息准备就绪');
        that._getProvinceData();
      },
      fail: function (res) {
        console.log('省fail');
        app._getNetWork({
          url: app.getNetAddresss('member.member-address.address'),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function (res) { },
          state: true
        });
      }
    });
  },

  //初始化城市
  _initDistrict(data, district) {
    if (!app._isTextEmpty(data)) {
      if (!app._isTextEmpty(data.myform.form)) {
        this.setData({
          isShowAddress: data.myform.base.address == 1 ? true : false
        });
      }
      this.setData({
        'addressObject.province': data.province,
        'addressObject.province_name': data.province_name,
        'addressObject.city': data.city,
        'addressObject.city_name': data.city_name,
        'addressObject.area': data.area,
        'addressObject.area_name': data.area_name,
        districtName: data.province_name + ' ' + data.city_name + ' ' + data.area_name,
        'addressObject.address': data.address
      });
      return;
    }

    if (!app._isTextEmpty(district)) {
      this.setData({
        'addressObject.province': district.itemValue1,
        'addressObject.province_name': district.itemName1,
        'addressObject.city': district.itemValue2,
        'addressObject.city_name': district.itemName2,
        'addressObject.area': district.itemValue3,
        'addressObject.area_name': district.itemName3
      });
      this.setData({
        districtName: district.itemName1 +
          ' ' +
          district.itemName2 +
          ' ' +
          district.itemName3
      });
    }
  },

  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log('省读取成功', res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          'selectAddressData[0].name': res.data[that.data.pickerValue[0]].areaname,
          'selectAddressData[0].id': res.data[that.data.pickerValue[0]].id,
          'selectAddressData[0].index': that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log('城市', '_data', _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log('城市读取成功', res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log('城市数据筛选', _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          'selectAddressData[1].name': _json[that.data.pickerValue[1]].areaname,
          'selectAddressData[1].id': _json[that.data.pickerValue[1]].id,
          'selectAddressData[1].index': that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log('地区', '_data', _data);
    console.log(_data);
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log('地区读取成功');
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log('地区数据筛选', _json);
        that.setData({
          districtData: _json
        });
        console.log('districtData', _json);
        that.setData({
          'selectAddressData[2].name': _json[that.data.pickerValue[2]].areaname,
          'selectAddressData[2].id': _json[that.data.pickerValue[2]].id,
          'selectAddressData[2].index': that.data.pickerValue[2]
        });
        console.log('over', that.data.selectAddressData);
      }
    });
  },

  //所在地选择显示
  showAddBtn() {
    this.setData({
      showAdd: true
    });
  },
  // 关闭选择地址
  _closeDateLw: function () {
    this.setData({
      showAdd: false
    });
  },

  // 地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      'pickerValue[0]': val[0],
      'pickerValue[1]': val[1],
      'pickerValue[2]': val[2]
    });
    this._initAddressInfo();
  },

  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let district = {
      itemValue1: seleData[0].id,
      itemName1: seleData[0].name,
      itemValue2: seleData[1].id,
      itemName2: seleData[1].name,
      itemValue3: seleData[2].id,
      itemName3: seleData[2].name
    };
    this._initDistrict('', district);
    this._closeDateLw();
  },

  getUserProfileTap() { //更新资料
    let that = this;
    wx.getUserProfile({
      desc: '获取用户信息',
      success: function (_info) {
        console.log("info:", _info);
        let is_info = {
          'nickName': _info.userInfo.nickName,
          'avatarUrl': _info.userInfo.avatarUrl,
          'gender': _info.userInfo.gender
        };
        that.setData({
          info: is_info
        });
        that.updateInfo();
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },
  choose(e){
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr,
      filePath: e.detail.avatarUrl,
      name: "file",
      success:(resdata)=> {
        var res = JSON.parse(resdata.data);
        if (res.result == 1) {
          that.setData({
            'form.avatar':res.data.img_url
          })
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
    });
    
  },
  input_handle(e){
    this.setData({
      "form.nickname":e.detail.value
    })
  },

  onChange(e) { //输入框值双向绑定
    let dataset = e.currentTarget.dataset
    let num = ''
    if (dataset.type == 'custom') {
      num = `diyField.form[${dataset.index}].value`
      this.setData({
        [num]: e.detail
      })
      return
    } else if (dataset.type == 'fixed') {
      this.setData({
        'form.field': e.detail
      })
    } else {
      num = `form.${dataset.typevalue}`
      console.log(num, e.detail)
      this.setData({
        [num]: e.detail
      })
    }
  },

  updateInfo() {
    let that = this;
    let urlStr = app.getNetAddresss('member.member-update.index');
    app._postNetWork({
      url: urlStr,
      data: {
        type: 2,
        info: that.data.info,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
          that.essentialInformation();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  essentialInformation() { //基本信息页数据
    let urlStr = app.getNetAddresss("member.member-info.user-info");
    let that = this
    app._getNetWork({
      url: urlStr,
      data: {
        basic_info: 1
      },
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          res.data.basic_info.forEach((item, index) => {
            let name = `registerBasicInfo.${item.field}`
            this.setData({
              [name]: item
            })
          });
          this.setData({
            'form.nickname': res.data.nickname,
            'form.avatar': res.data.avatar,
            'fileList[0].url': res.data.avatar_image,
            'diyform': res.data.diy_form,
            'nameOfTheMall': res.data.name,
            'changeNickname': res.data.can_update_nickname,
            'diyField': res.data.diy_field,
            'fixedDiyField': res.data.fixed_diy_field,
            'changePicture': res.data.can_update_avatar,
            'form.name': this.data.registerBasicInfo.name.value,
            'form.sex': this.data.registerBasicInfo.gender.value,
            'form.address': this.data.registerBasicInfo.address.value,
            'form.detailedAddress': this.data.registerBasicInfo.address.value.address,
            'diyStatus': res.data.diy_form.status,
            'customFormID': {
              'form_id': res.data.diy_form.id
            }
          })
          if (this.data.registerBasicInfo?.birthday?.value?.birthyear != "") { //生日赋值
            this.setData({
              'form.birthday': this.data.registerBasicInfo.birthday.value.birthyear + '-' + this.data.registerBasicInfo.birthday.value.birthmonth + '-' + this.data.registerBasicInfo.birthday.value.birthday,
              'currentDate':new Date(this.data.registerBasicInfo.birthday.value.birthyear,this.data.registerBasicInfo.birthday.value.birthmonth-1,this.data.registerBasicInfo.birthday.value.birthday).getTime(),
            })
          }
          if (this.data.registerBasicInfo.address?.value?.province_name != "") { //地址赋值
            this.setData({
              'districtName': this.data.registerBasicInfo.address.value.province_name + '  ' + this.data.registerBasicInfo.address.value.city_name + '  ' + this.data.registerBasicInfo.address.value.area_name
            })
          }
          if (this.data.registerBasicInfo.gender.value == 2) {
            this.setData({
              'sexLIst[0].checked': false,
              'sexLIst[1].checked': true
            })
          }
          if (this.data.fixedDiyField.length > 0) {
            this.setData({
              'form.field': res.data.fixed_diy_field[0].value
            })
          }
          if (this.data.diyStatus == 1) {
            this.setData({
              child:this.selectComponent('.dsfrom')
            })
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  modifyingUserInformation() { //提交用户信息修改
    if (this.data.registerBasicInfo.name && this.data.registerBasicInfo.name.show && this.data.registerBasicInfo.name.must == 1 && app._isTextEmpty(this.data.form.name)) {
      wx.showToast({
        icon: 'none',
        title: '请填写姓名',
        duration: 1500
      });
      return;
    }
    console.log(this.data.form.sex, '性别')
    if (this.data.registerBasicInfo.gender && this.data.registerBasicInfo.gender.show && this.data.registerBasicInfo.gender.must == 1 && app._isTextEmpty(this.data.form.sex)) {
      wx.showToast({
        icon: 'none',
        title: '请选择性别',
        duration: 1500
      });
      return;
    }
    if (this.data.registerBasicInfo.birthday && this.data.registerBasicInfo.birthday.show && this.data.registerBasicInfo.birthday.must == 1 && app._isTextEmpty(this.data.form.birthday)) {
      wx.showToast({
        icon: 'none',
        title: '请选择生日',
        duration: 1500
      });
      return;
    }
    if (this.data.registerBasicInfo.address && this.data.registerBasicInfo.address.show && this.data.registerBasicInfo.address.must == 1 && app._isTextEmpty(this.data.districtName)) {
      wx.showToast({
        icon: 'none',
        title: '请填写详细地址',
        duration: 1500
      });
      return;
    }

    if (this.data.fixedDiyField.length > 0) {
      let status = true
      let msg = ''
      this.data.fixedDiyField.forEach((item, index) => {
        if (this.data.form.field == "" && item.must == 1) {
          msg = '请填写' + item.name
          status = false
        }
      })
      if (!status) {
        wx.showToast({
          icon: 'none',
          title: msg,
          duration: 1500
        });
        return;
      }
    }

    if (!app._isTextEmpty(this.data.diyField) && this.data.diyField.form.length > 0 && this.data.diyField.form_open == 1) {
      let status = true
      let msg = ''
      this.data.diyField.form.forEach((item, index) => {
        if (app._isTextEmpty(item.value)) {
          msg = '请填写' + item.name
          status = false
        }
      })
      if (!status) {
        wx.showToast({
          icon: 'none',
          title: msg,
          duration: 1500
        });
        return;
      }
    }

    if (this.data.diyStatus == 1) {
      this.data.child.validation();
      console.log(this.data.child.data.isValidation)
      if (!this.data.child.data.isValidation) {
        return;
      }
    }


    let json = {
      avatar: this.data.form.avatar,
      nickname: this.data.form.nickname,
      name: this.data.form.name,
      gender: this.data.form.sex,
      birthday: this.data.form.birthday,
      custom_value: this.data.form.field,
    }
    //地址处理
    if (!app._isTextEmpty(this.data.form.address.province) && !app._isTextEmpty(this.data.form.address.city)) { //如果有回显地址值
      this.data.form.address.address = this.data.form.detailedAddress
      json['address'] = this.data.form.address
    }
    if (this.data.registerBasicInfo.address.show && this.data.addressObject.province_name != '' && this.data.addressObject.city_name != '') {
      this.setData({
        "addressObject.address": this.data.form.detailedAddress
      })
      json['address'] = this.data.addressObject
    }

    //自定义字段加值
    if (this.data.diyField.form.length > 0) {
      let json1 = {}
      this.data.diyField.form.forEach((item, index) => {
        json1[item.field] = item.value
        console.log('加值', item)
      })
      json['customDatas'] = json1
    }
    console.log('json', json)
    let that = this
    let urlStr = app.getNetAddresss("member.member-info.user-info-save");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          if (this.data.diyStatus == 1) {
             this.data.child.submit()
             wx.navigateBack({
              delta: 1
            });
          } else {
            wx.navigateBack({
              delta: 1
            });
            wx.showToast({
              icon: "success",
              title: "提交成功",
              duration: 1500,
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  addressToDealWith(value) { //地址处理
    let addressJson = {};
    addressJson['province'] = value[0].id
    addressJson['city'] = value[1].id
    addressJson['area'] = value[2].id
    addressJson['province_name'] = value[0].name
    addressJson['city_name'] = value[1].name
    addressJson['address'] = this.info_form.address
    return addressJson
  },


  postDiy(e) {
    let that = this;
    let formData = e.detail;
    // let formObject = {};
    // this.data.diydata.forEach(item => {
    //   if (item.type == 'diyimage') {
    //     formObject[item.name] = item.imgUrls;
    //   } else {
    //     formObject[item.name] = item.value;
    //   }
    // });
    // formData.push(formObject);

    let json = {
      form_data: formData,
      form_id: this.data.form_id,
      "form_type": "register"
    };
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '绑定成功',
            icon: 'none',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                that.gotourl();
                //要延时执行的代码
              }, 1500); //延迟时间
            },
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function (res) { }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})